//
//  YWAttendanceManager.m
//  maintain
//
//  Created by 郑想 on 16/2/22.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAttendanceManager.h"
#import "NSDate+Additions.h"
#import "YWAttendanceRecord.h"
#import "YWDBTool.h"
#import "YWLoginTool.h"
#import "YWAttendanceDBManager.h"
#import "YWMacro.h"
#import "WMHttpTool.h"
#import "YWCommonTool.h"
#import "YWEquipmentManager.h"
#import "YWBuildingManager.h"
#import "YWMeterReadingManager.h"
#import "YWConst.h"
#import "YWResourceManager.h"
#import "MJExtension.h"

//static BOOL isUploading = NO;

@interface YWAttendanceManager()
@property (nonatomic, strong) dispatch_group_t group;
//@property (nonatomic, strong) dispatch_queue_t serialQueue;
//@property (nonatomic, strong) dispatch_semaphore_t signal;
@end

@implementation YWAttendanceManager
YWSingletonM(Manager)

- (dispatch_group_t)group{
    if (!_group) {
        _group = dispatch_group_create();
    }
    return _group;
}

//- (dispatch_queue_t)serialQueue{
//    if (!_serialQueue) {
//        _serialQueue = dispatch_queue_create("uploadAttendanceRecordserialQueue", DISPATCH_QUEUE_SERIAL); //创建上传串行队列
//    }
//    return _serialQueue;
//}
//
//- (dispatch_semaphore_t)signal{
//    if (!_signal) {
//        _signal = dispatch_semaphore_create(1);
//    }
//    return _signal;
//}

//- (YWAttendanceOperateType)attendanceOperateType
//{
//    YWAttendanceRecord* record = [[YWDBTool shareDBTool] newestAttendanceRecord];
//    if (!record) {
//        return YWAttendanceOperateTypeCanArrive;
//    }
//    else {
//        if (record.leaveTime <= 0) { //下班时间为空
//            //判断上班时间是不是今天 如果是今天则可以签退下班  如果不是 则进行下一个上班
//
//            if ([self isToday:record.arriveTime]) {
//                return YWAttendanceOperateTypeCanLeave;
//            }
//            else {
//                return YWAttendanceOperateTypeCanArrive;
//            }
//        }
//        else {
//            return YWAttendanceOperateTypeCanArrive;
////            //判断下班时间是不是今天 如果是则说明今天已经签到签退完成
////            if ([self isToday:record.leaveTime]) {
////                return YWAttendanceOperateTypeNoAll;
////            }
////            else {
////                return YWAttendanceOperateTypeCanArrive;
////            }
//        }
//    }
//}

- (YWAttendanceRecord*)newestAttendanceRecord
{
    return [[YWAttendanceDBManager shareManager] newestAttendanceRecord];
}

- (BOOL)updateAttendanceRecordWithRecord:(YWAttendanceRecord*)attendanceRecord
{
    return [[YWAttendanceDBManager shareManager] updateAttendanceRecordWithRecord:attendanceRecord];
}

- (NSArray*)attendanceRecordWithPage:(NSInteger)page
{
    return [[YWAttendanceDBManager shareManager] attendanceRecordWithPage:page];
}

- (BOOL)updateAttendance:(YWAttendanceRecord*)attendance withRecordId:(NSString*)recordId
{
    return [[YWAttendanceDBManager shareManager] updateAttendance:attendance withRecordId:recordId];
}

- (void)submitAttendanceRecord:(YWAttendanceRecord *)record pistures:(NSArray *)pictures completeBlock:(void (^)(BOOL))complete{
//    if (record == nil) {
//        return;
//    }
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        dispatch_group_enter(self.group);
            if (pictures.count > 0) {
                [[YWResourceManager shareManager] uploadPatrolPictureToAliyunOSS:pictures complete:^(BOOL isError, NSArray* uploadPictures) {
                    [self postAttendanceRecord:record uploadPictures:uploadPictures error:isError completeBlock:^(BOOL succeed) {
                        if (complete) {
                            complete(succeed);
                        }
                    }];
                }];
            }else{
                [self postAttendanceRecord:record uploadPictures:nil error:NO completeBlock:^(BOOL succeed) {
                    if (complete) {
                        complete(succeed);
                    }
                }];
            }
//        dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
//    });
}

//- (NSString*)savefilePath:(NSString*)fileName
//{
//    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
//    return filePath;
//}

- (void)postAttendanceRecord:(YWAttendanceRecord *)record uploadPictures:(NSArray *)pictures error:(BOOL)isError completeBlock:(void (^)(BOOL))complete{
//    [[YWMeterReadingManager shareManager] updatePatrolPictureWithArray:pictures];
    if (!isError) {
        [[YWMeterReadingManager shareManager] updatePatrolPictureWithArray:pictures];
        NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
        if (headersDic == nil) {
            //dispatch_group_leave(self.group);
            if (complete) {
                complete(NO);
            }
            return;}
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        if (record.qrcodeId) {
            [params setValue:record.qrcodeId forKey:@"qrcodeId"];
        }
        if (record.locationId) {
            [params setValue:@(record.locationId) forKey:@"locationId"];
        }
        
        [params setValue:record.arriveRemark?:@"" forKey:@"note"];
        [params setValue:@(record.type) forKey:@"type"];
        if (record.locationText) {
            [params setValue:record.locationText forKey:@"position"];
        }
        [params setValue:record.coordinate?:@"" forKey:@"coordinate"];
        
        [pictures enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
            [params setValue:picture.bigUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].url", (unsigned long)idx]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].thumbnailUrl", (unsigned long)idx]];
            [params setValue:picture.smallUrl ?: @"" forKey:[NSString stringWithFormat:@"pictures[%lu].previewUrl", (unsigned long)idx]];
        }];
        long long executeTime = [YWCommonTool numberWithTime:record.arriveTime]*1000;
        [params setObject:@(executeTime) forKey:@"clientExecuteTime"];
        long long nowTime = [YWCommonTool numberWithTime:[[NSDate date] timeIntervalSince1970]*1000];
        [params setObject:@(nowTime) forKey:@"clientCurrentTime"];
        /*
        id rememberTime = [NSKeyedUnarchiver unarchiveObjectWithFile:[self savefilePath:KYWRememberSystemUptime]];
        long long rememberSystemUptime = [rememberTime doubleValue];
        NSTimeInterval nowSystemUptime =[[NSProcessInfo processInfo] systemUptime];
        long long UptimeJetLag = nowSystemUptime - rememberSystemUptime;
        long long dateJetLag = (nowTime - executeTime)/1000;
        long long timeJetLag = dateJetLag - UptimeJetLag;
        if (timeJetLag > 600 || timeJetLag < -600) {
            [self updateAttendanceUploadStatus:YWAttendanceUploadStatusChangeTime withAttendanceRecordId:record.recordId];
//            [[NSNotificationCenter defaultCenter] postNotificationName:KUpdateAttendanceUploadStatusNotification object:nil];
            return;
        }*/
        
        NSString *url = [YWCommonTool getAttendanceUrl];
        YWLog(@"提交签到记录url:%@,params:%@",url,params);
        
        [[WMHttpTool shareHttpTool] postWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                if ([json isKindOfClass:[NSDictionary class]]) {
                    [[YWAttendanceManager shareManager] updateAttendanceRecordWithRecord:record];
                    
                    NSDictionary* dic = (NSDictionary*)json;
                    id recordId = [dic objectForKey:@"attendanceRecordId"];
                    NSTimeInterval sytemTime = [[dic objectForKey:@"createTime"] longLongValue]/1000;
                    NSString * oldRecordId = record.recordId;
                    record.uploadStatus = YWAttendanceUploadStatusSucceed;
                    record.recordId = [NSString stringWithFormat:@"%@",recordId];
                    record.arriveTime = sytemTime;
                    //更新记录id
                    [[YWAttendanceManager shareManager] updateAttendance:record withRecordId:oldRecordId];
                    //更新记录里的图片的关联id
                    [[YWMeterReadingManager shareManager] updatePatrolPictureRecordId:record.recordId WithOldRecordId:oldRecordId];
//                    [[NSNotificationCenter defaultCenter] postNotificationName:KUpdateAttendanceUploadStatusNotification object:nil];
                }
//                dispatch_group_leave(self.group);
                if (complete) {
                    complete(YES);
                }
            });
        } failure:^(NSHTTPURLResponse* response, NSError* error) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                YWLog(@"%s,error:%@", __func__, error.localizedDescription);
                //这里判断状态码(上传失败的
                [self updateAttendanceUploadStatus:YWAttendanceUploadStatusFailure withAttendanceRecordId:record.recordId];
//                [[NSNotificationCenter defaultCenter] postNotificationName:KUpdateAttendanceUploadStatusNotification object:nil];
//                dispatch_group_leave(self.group);
                if (complete) {
                    complete(NO);
                }
            });
        }];
    }else {
        [self updateAttendanceUploadStatus:YWAttendanceUploadStatusFailure withAttendanceRecordId:record.recordId];
//        [[NSNotificationCenter defaultCenter] postNotificationName:KUpdateAttendanceUploadStatusNotification object:nil];
//        dispatch_group_leave(self.group);
        if (complete) {
            complete(NO);
        }
    }
}

- (NSArray*)attendanceRecordWithUploadStatusFail{
    return [[YWAttendanceDBManager shareManager] attendanceRecordWithUploadStatusFail];
}

- (BOOL)updateAttendanceUploadStatus:(NSInteger)uploadStatus withAttendanceRecordId:(NSString*)recordId
{
    return [[YWAttendanceDBManager shareManager] updateAttendanceUploadStatus:uploadStatus withAttendanceRecordId:recordId];
}

- (BOOL)updateAttendanceRecordWithAttendRecordArray:(NSArray *)attendanceRecordArray{
    return [[YWAttendanceDBManager shareManager] updateAttendanceRecordWithAttendRecordArray:attendanceRecordArray];
}

- (void)getAttendanceRecordWithAttendanceRecordId:(NSString*)attendanceRecordId WithComplete:(void(^)(YWAttendanceRecord *record))complete{
    NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
    if (headersDic == nil) {if (complete) {complete(nil);};return;}
    NSString *url = [YWCommonTool getAttendanceRecordUrl];
    NSString *withUrl = [NSString stringWithFormat:@"%@/%@",url,attendanceRecordId];
    YWLog(@"url =%@",withUrl);
    [[WMHttpTool shareHttpTool] getWithUrl:withUrl params:nil success:^(NSHTTPURLResponse* response, id json) {
        //获取签到记录详情
         YWAttendanceRecord *attendanceRecord = [YWAttendanceRecord mj_objectWithKeyValues:json];
        [[YWAttendanceManager shareManager] updateAttendanceRecordWithRecord:attendanceRecord];
        if (complete) {
            complete(attendanceRecord);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (complete) {
            complete(nil);
        }
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}

- (void)getAboutMeAttendanceWithPage:(NSInteger)page pageSize:(NSInteger)pageSize WithComplete:(void (^)(BOOL success))complete{
    NSDictionary *headers = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
    [WMHttpTool shareHttpTool].HTTPHeaders = headers;
    if (headers == nil) {if (complete) {complete(NO);}return;}
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (page) {
        [params setValue:@(page) forKey:@"page"];
    }
    if (pageSize) {
        [params setValue:@(pageSize) forKey:@"pageSize"];
    }
    NSString *url = [YWCommonTool getAboutMeAttendanceRecordUrl];
    YWLog(@"url -- %@,%@",url,params);
    [[WMHttpTool shareHttpTool] getWithUrl:url params:params success:^(NSHTTPURLResponse* response, id json) {
        NSArray* attendanceRecordArray = [YWAttendanceRecord mj_objectArrayWithKeyValuesArray:json];
        [self updateAttendanceRecordWithAttendRecordArray:attendanceRecordArray];
        if (complete) {
            complete(YES);
        }
    } failure:^(NSHTTPURLResponse* response, NSError* error) {
        if (![[WMHttpTool shareHttpTool] existenceNetwork]) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
        }else{
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"requestFailed", nil)];
        }
        if (complete) {
            complete(NO);
        }
        YWLog(@"%s,error:%@", __func__, error.localizedDescription);
    }];
}
//上传失败后重新上传
//- (void)uploadFailAttendanceInfo{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        if (![YWLoginTool isLogin]) {
//            return;
//        }
//        if (isUploading == YES) {
//            return;
//        }
//        isUploading = YES;
//        
//        NSArray * uploadFailAttendanceRecords = [self attendanceRecordWithUploadStatusFail];
//        [uploadFailAttendanceRecords enumerateObjectsUsingBlock:^(YWAttendanceRecord *  _Nonnull attendanceRecord, NSUInteger idx, BOOL * _Nonnull stop) {
//            NSArray* pictures = [[YWDBTool shareDBTool] recordPictureWithRecordId:attendanceRecord.recordId recordType:YWPictureRecordTypeAttendance];
//            
//            dispatch_group_enter(self.group);
//            if (pictures.count > 0) {
//                [[YWResourceManager shareManager] uploadPatrolPictureToAliyunOSS:pictures complete:^(BOOL isError, NSArray* uploadPictures) {
//                    [self postAttendanceRecord:attendanceRecord uploadPictures:uploadPictures error:isError];
//                }];
//            }else{
//                [self postAttendanceRecord:attendanceRecord uploadPictures:nil error:NO];
//            }
//            dispatch_group_wait(self.group, DISPATCH_TIME_FOREVER);
//            
//            if (idx == uploadFailAttendanceRecords.count-1) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [[NSNotificationCenter defaultCenter] postNotificationName:KPushBackgroundUploadRecordSuccessNotification object:nil];
//                });
//            }
//        }];
//        
//        isUploading = NO;
//    });
//}


//- (NSString*)showStatusStrWithRecord:(YWAttendanceRecord*)attendanceRecord
//{
//    if (attendanceRecord.leaveTime <= 0) {
//        if (![self isToday:attendanceRecord.arriveTime]) {
//            return @"异常";
//        }
//    }
//    return @"出勤";
//}

@end
